﻿using System;
using System.Collections.Specialized;
using System.Linq;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;
using Transitionals.Controls;

namespace LaserTag.Infrastructure.RegionAdapters
{
    public class TransitionElementRegionAdapter : RegionAdapterBase<TransitionElement>
    {
        public TransitionElementRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory)
            : base(regionBehaviorFactory)
        {
        }

        protected override void Adapt(IRegion region, TransitionElement regionTarget)
        {
            bool contentIsSet = regionTarget.Content != null;

            if (contentIsSet)
            {
                throw new InvalidOperationException("TransitionElementRegionAdapter already has content set!");
            }

            region.ActiveViews.CollectionChanged += (sender, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    regionTarget.Content = region.ActiveViews.FirstOrDefault();
                }
            };

            region.Views.CollectionChanged += (sender, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add && region.ActiveViews.Count() == 0)
                {
                    region.Activate(e.NewItems[0]);
                }
            };
        }

        protected override IRegion CreateRegion()
        {
            return new SingleActiveRegion();
        }
    }
}
